package middleware

import (
	"encoding/gob"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

type LoginMiddlewareBuilderJWT struct {
	paths map[string]struct{}
}

func NewLoginJWTMiddleware() *LoginMiddlewareBuilderJWT {
	return &LoginMiddlewareBuilderJWT{
		paths: make(map[string]struct{}),
	}
}
func (l *LoginMiddlewareBuilderJWT) SetPath(path string) {
	l.paths[path] = struct{}{}
}
func (l *LoginMiddlewareBuilderJWT) Build() gin.HandlerFunc {
	gob.Register(time.Now())
	return func(ctx *gin.Context) {
		path := ctx.Request.URL.Path
		_, value := l.paths[path]
		if value {
			return
		}
		session := sessions.Default(ctx)
		userId := session.Get("userId")
		if userId == nil {
			ctx.AbortWithStatus(http.StatusUnauthorized)
			return
		}
		updateTime := session.Get("update_time")
		session.Options(sessions.Options{
			MaxAge: 60,
		})
		now := time.Now()
		if updateTime == nil {
			session.Set("update_time", now)
			if err := session.Save(); err != nil {
				panic(err)
			}
			return
		}
		updateTimeVal := updateTime.(time.Time)
		seconds := now.Sub(updateTimeVal).Seconds()
		if seconds > 10 {
			session.Set("update_time", now)
			if err := session.Save(); err != nil {
				panic(err)
			}
			return
		}

	}
}
